package ext.tianma.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.method.RemoteAccess;
import wt.method.RemoteMethodServer;
import wt.org.DirectoryContextProvider;
import wt.org.GenericDirectoryContextProvider;
import wt.org.OrganizationServicesHelper;
import wt.org.WTUser;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.util.WTException;
import wt.util.WTProperties;
/**
 * 用用户替代名替换用户名并删除替代名
 * @author deng
 *
 */
public class UpdateUserName1 implements RemoteAccess{
	private static String wtHome = "";
	private static String RegEx = "[A-Z][0-9]{5,9}";// 正则表达式规则
	static {
		WTProperties wtproperties;
		try {
			wtproperties = WTProperties.getLocalProperties();
			wtHome = wtproperties.getProperty("wt.home", "");
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		try {
			RemoteMethodServer rms = RemoteMethodServer.getDefault();
			rms.setUserName("wcadmin");
			rms.setPassword("tmadmin");
			rms.invoke("updateUserName", UpdateUserName1.class.getName(),null,null,null);
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 修改用户名
	 * 
	 * @return
	 * @throws IOException
	 * @throws WTException
	 */
	public static void updateUserName() throws IOException, WTException {
		String name = "alternateUserName1";//替代名1
		String nameUser = "";
		String alternateName ="";
		long start = System.currentTimeMillis();
		Enumeration enum1 = OrganizationServicesHelper.manager.allUsers();
		String filepath = wtHome+ File.separator + "temp"+ File.separator + "modifyLdap.log";
		File myFilePath = new File(filepath);
	      if(!myFilePath.exists()){
	        myFilePath.createNewFile();
	      }
		FileWriter fileWriter = new FileWriter(myFilePath);
		String filepathFail = wtHome+ File.separator + "temp"+ File.separator + "modifyLdapFail.log";
		File myFilePathFail = new File(filepathFail);
	      if(!myFilePathFail.exists()){
	    	  myFilePathFail.createNewFile();
	      }
		FileWriter fileWriterFail = new FileWriter(myFilePathFail);
		//获得所有用户
		while (enum1.hasMoreElements()) {
            Object obj = (Object) enum1.nextElement();
            if (obj instanceof WTUser) {
                WTUser user = (WTUser) obj;
                nameUser = user.getName();
             // 正则表达式规则
        	    String regEx = RegEx;
        	    // 编译正则表达式
        	    Pattern pattern = Pattern.compile(regEx);
        	    Matcher matcher = pattern.matcher(nameUser);
        	    // 查找字符串中是否有匹配正则表达式的字符/字符串
        	    boolean rs = matcher.matches();
                if(!nameUser.equals("Administrator") && !rs) {
					try {
						alternateName = getAlternateName(user,name);
						if(null == alternateName) {
							fileWriterFail.write("--->>> Modify User: " + nameUser + "替代名为空，"+"更新失败!\n");
							continue;
						}
						Matcher matcherAlt = pattern.matcher(alternateName);
						boolean rsAlt = matcherAlt.matches();
						//校验替代用户名数据是否符合工号要求
                        if(alternateName != null && !alternateName.equals("") && rsAlt) {
                        	//通过替代用户名获取用户，判断是否存在用户
                        	WTUser wtUser = getUserByName(alternateName);
                        	if(wtUser == null) {
                        		user.setName(alternateName);//用替代名1替换用户名
//	                            user.getAttributes().removeAttribute("uid");//删除替代名
	                            OrganizationServicesHelper.manager.updatePrincipal(user);//更新用户
	                            fileWriter.write("--->>> Modify User: " + nameUser +"替代名"+ alternateName+" success!\n");
                        	}else {
                        		fileWriterFail.write("--->>> Modify User: " + nameUser + "替代名"+ alternateName+" fail!用户已经存在\n");
                        	}
                        }else {
                        	fileWriterFail.write("--->>> Modify User: " + nameUser + "替代名"+ alternateName+" fail!工号格式不对\n");
                        }
					} catch (WTException e) {
						e.printStackTrace();
						fileWriterFail.write("--->>> Modify User: " + nameUser + "替代名"+ alternateName+" fail!\n");
						continue;
					} catch (Exception e) {
						e.printStackTrace();
						fileWriterFail.write("--->>> Modify User: " + nameUser + "替代名"+ alternateName+" fail!\n");
						continue;
					}
                }
            }
        } 
		fileWriter.close();
		fileWriterFail.close();
		long end = System.currentTimeMillis();
		System.out.println("****** 执行修改用户名接口共用时间:" + (end - start) / 1000 + "秒");
	}
	/**
	 * 获得用户替代名
	 * @param paramWTUser
	 * @param paramString
	 * @return
	 * @throws WTException
	 */
	public static String getAlternateName(WTUser paramWTUser, String paramString) throws WTException {
	    String str = null;
	    Enumeration localEnumeration = paramWTUser.getAttributes().getValues("uid");

	    ArrayList localArrayList = Collections.list(localEnumeration);
	    localArrayList.remove(paramWTUser.getName());
	    if ((paramString.equals("alternateUserName1")) && (localArrayList.size() > 0))
	      str = (String)localArrayList.get(0);
	    else if ((paramString.equals("alternateUserName2")) && (localArrayList.size() > 1))
	      str = (String)localArrayList.get(1);
	    else if ((paramString.equals("alternateUserName3")) && (localArrayList.size() > 2))
	      str = (String)localArrayList.get(2);
	    else if ((paramString.equals("alternateUserName4")) && (localArrayList.size() > 3)) {
	      str = (String)localArrayList.get(3);
	    }
	    return str;
	  }
	/**
	 * 根据name获得用户
	 * @param name
	 * @return
	 */
	private static WTUser getUserByName1(String name) {
		WTUser user = null;
		try {
			String[] defaultService = OrganizationServicesHelper.manager.getDirectoryServiceNames();
			DirectoryContextProvider dcp = OrganizationServicesHelper.manager
					.newDirectoryContextProvider(defaultService, new String[] { "subtree" });
			Enumeration eee = OrganizationServicesHelper.manager.findLikeUsers("name", name,
					new GenericDirectoryContextProvider(defaultService));
			if (eee.hasMoreElements())
				user = (WTUser) eee.nextElement();
		} catch (WTException wte) {
			wte.printStackTrace();
		}
		return user;
	}
	//根据用户名查询WTUser对象
	public static  WTUser getUserByName(String username) throws WTException{
		WTUser user = null ;
		QuerySpec qs = new QuerySpec(WTUser.class);
		SearchCondition sc = new SearchCondition(WTUser.class,WTUser.NAME,"=",username);
		qs.appendWhere(sc);
		QueryResult qr = PersistenceHelper.manager.find(qs);
		while(qr.hasMoreElements())
		{
			user = (WTUser)qr.nextElement();
		}
		return user;
	}
}
